//index.js
var CryptoJS = require('../../utils/crypto-js');

//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hello World',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  //事件处理函数
  bindViewTap: function() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
    } else if (this.data.canIUse){
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    let params = {
      Action: "TextTranslate",
      SecretId: "AKIDX7ZpwuJ2HZgcMutQUO6dx51lKikbxQ6a",
      Nonce: Math.floor(Math.random() * 100000),
      Timestamp: Math.round(new Date().getTime() / 1000).toString(),
      Version: "2018-03-21",
      ProjectId: 10,
      Source: "en",
      Target: "zh",
      Region: "ap-guangzhou"
    };

    //待翻译内容
    params.SourceText="hello";

    let sParams = this.objKeySort(params);

    let paramStr = Object.keys(sParams).map(function (key) {
      return key + "=" + sParams[key];
    }).join("&");
   
    let url = "GETtmt.tencentcloudapi.com/?" + paramStr;
    var hash = CryptoJS.HmacSHA1(url, "RtEONA4pOlz1tcAWgeU9ct9E5pOm6aw7"); 
    var sign = CryptoJS.enc.Base64.stringify(hash) ;
    params.Signature = sign;

    wx.request({
      url: 'https://tmt.tencentcloudapi.com/',
      // method: "POST",
      data: params,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data.Response.TargetText)
      }
    })
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  },
  objKeySort :function (obj) {//排序的函数
    var newkey = Object.keys(obj).sort();
    　　//先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    var newObj = {};//创建一个新的对象，用于存放排好序的键值对
    for(var i = 0; i<newkey.length; i++) {//遍历newkey数组
      newObj[newkey[i]] = obj[newkey[i]];//向新创建的对象中按照排好的顺序依次增加键值对
    }
    return newObj;//返回排好序的新对象
  }
})
